package com.google.project.client.ProjectManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.UsersDTO;
public class PMProjectList extends Composite {


	private static final Binder binder = GWT.create(Binder.class);
	@UiField(provided = true) CellTable<ProjectDTO> ctbProjectList = new CellTable<ProjectDTO>();
	@UiField ListBox cboStatus;
	@UiField TextBox txtProjectName;
	@UiField Button searchBtn;
	@UiField SimplePager pager;

	interface Binder extends UiBinder<Widget, PMProjectList> {
	}
  int load =0;
	// _____________________________Common variable_____________________________
	private final ProjectServiceAsync projectService = GWT
			.create(ProjectService.class);
	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);
	UsersDTO currUser = new UsersDTO();
	List<ProjectDTO> listProject = new ArrayList<ProjectDTO>();

	// End__________________________Common variable_____________________________

	// ________________________________Contructor_______________________________
	public PMProjectList() {

		initWidget(binder.createAndBindUi(this));
		fillCbStatus(1); //list dự án đang triển khai
		getProjectByUser(1);

	}
	public PMProjectList(int status) {
		initWidget(binder.createAndBindUi(this));
		fillCbStatus(status);
		getProjectByUser(status);
	}
	//lấy thông tin user từ session -->get project by status && userID
	public void getProjectByUser(final int statusProj){
		loginService.getCurrentUserDTO(new AsyncCallback<UsersDTO>() {

			@Override
			public void onSuccess(UsersDTO result) {
				// TODO Auto-generated method stub
				currUser = result;
				initTable();				
				bindData(statusProj);
			}

			@Override
			public void onFailure(Throwable caught) {
			}
		});
	}
	// End_____________________________Contructor_______________________________

	// _____________________________Common function_____________________________
	/*
	 * Fill data to cell table - ctbProjectList
	 */
	private native void fomatTable()
	/*-{
		$wnd.fomatTable();
	}-*/;
	/***
	 * Lấy danh sách dự án theo userID và trạng thái project
	 * 0-mới, 1-đang tiến hành
	 */
	public void bindData(final int status) {

		projectService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {

			@Override
			public void onSuccess(List<ProjectDTO> result) {
				listProject = result;
				List<ProjectDTO> list=new ArrayList<ProjectDTO>();
				for (ProjectDTO projectDTO : listProject) {
					if(projectDTO.getStatus()==status && projectDTO.getUserId().equals(currUser.getUserId())){
						list.add(projectDTO);
					}
				}
				LoadData(list);

			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("load fail");

			}
		});
	}

	// Khoi tao Cell Table
	public void initTable() {

		TextColumn<ProjectDTO> stt = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				return project.getIndex() + "";
			}
		};

		// Cot Ten du an - hyberlink ket noi voi bang Chi tiet

		Column<ProjectDTO, String> projectNameColumn = new Column<ProjectDTO, String>(
				new ClickableTextCell()) {
			@Override
			public String getValue(ProjectDTO object) {
				return object.getProjectName();
			}
		};
		
		projectNameColumn
				.setFieldUpdater(new FieldUpdater<ProjectDTO, String>() {
					@Override
					public void update(int index, ProjectDTO project,
							String value) {
						// Chuyen sang bang chi tiet du an
						PMEntrypoint.get().PMProjectDetail(
								project.getProjectID());
					}
				});

		// Cot Ten du an
		TextColumn<ProjectDTO> projectCodeColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				return project.getProjectCode();
			}
		};
		// Cot Ten du an
		TextColumn<ProjectDTO> complete = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				return project.getComplete() + "%";
			}
		};

		// Cot Ngay bat dau
		TextColumn<ProjectDTO> startDateColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				return CommonFuntion.convertToDate(new Date(project
						.getStartDate()));
			}
		};

		// Cot Ngay ket thuc
		TextColumn<ProjectDTO> dueDateColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				
				if(project.getStatus()==0||project.getStatus()==1)
				{
					return CommonFuntion.convertToDate(new Date(project
							.getDueDate()));
				}
				else
				{
					return CommonFuntion.convertToDate(new Date(project
							.getFinishDate()));
				}
				
			}
		};

		TextColumn<ProjectDTO> statusColumn = new TextColumn<ProjectDTO>() {
			@Override
			public String getValue(ProjectDTO project) {
				int status = project.getStatus();
				String _status = "";
				if (status == 0) {
					_status += "Dự án mới";
				} else if (status == 1) {
					_status += "Đang tiến hành";
				} else if (status == 2) {
					_status += "Đã hoàn thành";
				}
				if(status==3)
				{
					return  "Ngừng thực hiện";
				}
				return _status;
			}
		};

		// Setup width
		ctbProjectList.setWidth("100%", true);
		ctbProjectList.setPageSize(5);
		ctbProjectList.setPageStart(1);
		ctbProjectList.addColumn(stt, "STT");
		ctbProjectList.setColumnWidth(stt, 5.0, Unit.PCT);
		projectNameColumn.setCellStyleNames("celltable");
		ctbProjectList.setStyleName("ttable");
		ctbProjectList.addColumn(projectCodeColumn, "Mã dự án");
		ctbProjectList.addColumn(projectNameColumn, "Tên dự án");
		ctbProjectList.setColumnWidth(projectNameColumn, 25.0, Unit.PCT);
		
		
		ctbProjectList.addColumn(complete, "Hoàn thành");

		ctbProjectList.getColumn(
				ctbProjectList.getColumnIndex(projectNameColumn))
				.setHorizontalAlignment(HasAlignment.ALIGN_LEFT);

		
		// ctbProjectList.setColumnWidth(projectCodeColumn, 15.0, Unit.PCT);

		ctbProjectList.addColumn(startDateColumn, "Ngày bắt đầu");
		// ctbProjectList.setColumnWidth(startDateColumn, 13.0, Unit.PCT);
		ctbProjectList
				.getColumn(ctbProjectList.getColumnIndex(startDateColumn))
				.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);

		ctbProjectList.addColumn(dueDateColumn, "Ngày kết thúc");
		// ctbProjectList.setColumnWidth(dueDateColumn, 13.0, Unit.PCT);
		ctbProjectList.getColumn(ctbProjectList.getColumnIndex(dueDateColumn))
				.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);

		ctbProjectList.addColumn(statusColumn, "Trạng thái");
		// ctbProjectList.setColumnWidth(statusColumn, 15.0, Unit.PCT);
	}

	/*
	 * @param projectList
	 */
	public void LoadData(List<ProjectDTO> projectList) {

		// SimplePager
		pager.setDisplay(ctbProjectList);
		pager.setPageSize(5);

		// Create a data provider.
		ListDataProvider<ProjectDTO> dataProvider = new ListDataProvider<ProjectDTO>();

		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbProjectList);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		int count = 1;
		List<ProjectDTO> list = dataProvider.getList();
		for (ProjectDTO project : projectList) {
			if (project.getUserId().equals(currUser.getUserId())) {
				project.setIndex(count);
				count++;
				list.add(project);
			}
		}

	}

	/***
	 * Fix data to cboStatus
	 */
	public void fillCbStatus(int status) {
		cboStatus.addItem("---Tất cả---", "-1");
		cboStatus.addItem("Dự án mới", "0");
		cboStatus.addItem("Đang tiến hành", "1");
		cboStatus.addItem("Đã hoàn thành", "2");
		cboStatus.addItem("Ngừng thực hiện", "3");
		cboStatus.setSelectedIndex(status+1);
	}

	// End__________________________Common function_____________________________

	// ___________________________________Event_________________________________
	/*
	 * @param event click to cboStatus
	 */

	@UiHandler("searchBtn")
	void onSearchBtnClick(ClickEvent event) {
		fomatTable();
		List<ProjectDTO> searchData = new ArrayList<ProjectDTO>();
		Boolean check = true;
		for (ProjectDTO project : listProject) {
			if (!project.getUserId().equals(currUser.getUserId())) {
				check = false;
			}
			if (!cboStatus.getValue(cboStatus.getSelectedIndex()).equals("-1")) {
				check = check
						&& (cboStatus.getValue(cboStatus.getSelectedIndex())
								.equals(project.getStatus() + ""));
			}
			if (txtProjectName.getValue().trim() != null
					&& !txtProjectName.getValue().trim().equals("")) {
				check = check
						&& (project.getProjectName().contains(txtProjectName
								.getValue().trim()));
			}
			if (check) {
				searchData.add(project);

			}
			check = true;
		}
		LoadData(searchData);
	}
}
